Skip to main content

Median of Two Sorted Arrays

Question

What is the most efficient algorithm for finding the median of two sorted arrays of equal length?

Example 1
Input Array 1: [1, 3, 5]
Input Array 2: [2, 4, 6]
Output: 3.5

Solution

all//Median of Two Sorted Arrays.py


def findMedianSortedArrays(nums1, nums2):
merged_array = sorted(nums1 + nums2)

if len(merged_array) % 2 == 0:
mid_index1 = len(merged_array) // 2
mid_index2 = mid_index1 - 1
median = (merged_array[mid_index1] + merged_array[mid_index2]) / 2
else:
median = merged_array[len(merged_array) // 2]

return median